package com.airikeji.hr.rabbitmq;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.airikeji.hr.common.Const;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;


/**
 * @Author huangrui
 * @Date 2021/7/8 17:44
 * @Version 1.0
 */
@Slf4j
@Component
public class RabbitMQReceiver {

    @RabbitListener(queues="queue.2")
    public void fanoutReceive(Message message , @Headers Map headers, Channel channel) throws UnsupportedEncodingException {
        // 采用手动应答模式, 手动确认应答更为安全稳定
        try {
            Long deliverTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
            // 确认该条消息（这里应该根据业务去写）
            if(true){
                channel.basicAck(deliverTag,false);
                log.info("收到的消息是:"+ new String(message.getBody(),"utf-8"));
            }else{
                // 消费失败，消息重返队列
                channel.basicNack(deliverTag,false,true);
                log.info("消息:"+ new String(message.getBody(),"utf-8") + "接收失败！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(queues="queue.direct.1")
    public void directReceive(Message message, @Headers Map headers, Channel channel) throws IOException {
        try {
            log.info("收到的消息是:"+ new String(message.getBody(),"utf-8"));
            //主动异常
//            int m = 1/0;
            //手动签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
        catch (Exception e) {
            log.info("捕获到异常,拒绝重新入队---消息ID---{}",headers.get("spring_returned_message_correlation"));
            //异常，ture 重新入队
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }
    }

}
